package com.dhcc.DRGsHosp.facade.impl;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.smslib.AGateway;
import org.smslib.IInboundMessageNotification;
import org.smslib.IOutboundMessageNotification;
import org.smslib.InboundMessage;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.OutboundBinaryMessage;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;

//import com.dhcc.sms.manage.common.util.PropertyUtil;
/**
 * @title		:SendMessageFacadeImpl.java
 * @description	:
 * @author		:pcnicky
 * @date		:2015年7月13日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
public class SendMessageFacadeImpl{
	private static Map<String,String> comMap;
	private static String SEND_SMS_GROUP = "smsgruop";	// 用于发送短信的组名
	private boolean rec_msg_remove = true;				// 收到,处理短信之后,是否删除当前短信.默认删除

	private static final SendMessageFacadeImpl srv = new SendMessageFacadeImpl();

	static List<InboundMessage> readMessages=null;
	/**
	 * 获取可用端口
	 */
	
	static{
		comMap=FindSmsComsFacadeImpl.findComList();
	}
	public static SendMessageFacadeImpl getInstance()
	{
		try {
			if(!srv.isStarted()){
				srv.startService();
				//收取已接收的短信（原因监听器未启动监听不到）
				readMessages = srv.readMessages();
				if(readMessages!=null&&readMessages.size()>0){
					class ReadMsgThread extends Thread{ 
					
						public void run(){
							for (InboundMessage msg : readMessages) {
								System.out.println(msg);
								try{
									//处理收到的短信
									ParseMessageFacadeImpl.parse(msg.getOriginator(),"",msg.getText());
								}catch (Exception e) {
									System.out.println("不是文本信息");
								}finally{
									// 删除收到的短信
									try {
										Service.getInstance().deleteMessage(msg);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						} 
					} 
			        Thread t = new ReadMsgThread();
			        t.start();  
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SendMessageFacadeImpl.srv;
	}
	/**
	 * 功能：启动服务
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @throws Exception
	 */
	public void startService() throws Exception{
		InboundNotification inboundNotification = new InboundNotification();
		OutboundNotification outboundNotification = new OutboundNotification();
		Service.getInstance().S.SERIAL_POLLING = true;  //启用轮循模式  
		Iterator<String> iter = comMap.keySet().iterator();
		while (iter.hasNext()) {
		    String cgsn = iter.next();
		    String com = comMap.get(cgsn);
			SerialModemGateway gateway = new SerialModemGateway("modem."+com, com, 9600, "wavecom", "");
			gateway.setInbound(true);	//设置true，表示该网关可以接收短信,根据需求修改
			gateway.setOutbound(true);//设置true，表示该网关可以发送短信,根据需求修改
			//gateway.setSimPin("0000");//sim卡锁，一般默认为0000或1234
			//gateway.setSmscNumber("+306942190000");//短信服务中心号码
			Service.getInstance().addGateway(gateway);//将网关添加到短信猫服务中
		}
		for (int i = 0; i < comMap.size(); i++) {
			
		}
		Service.getInstance().setInboundMessageNotification(inboundNotification);
		Service.getInstance().setOutboundMessageNotification(outboundNotification);
		Service.getInstance().startService();
	}
	/**
	 * @describe: 设置:收到,处理短信之后,是否删除当前短信.默认删除
	 * @param rec_msg_flag: true:删除 false:不删除
	 * @date:2010-3-2
	 */
	public void setRec_msg_remove(boolean rec_msg_remove) {
		this.rec_msg_remove = rec_msg_remove;
	}
	/**
	 * 
	 * 功能：发彩信
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param phone 	号码（不支持多个）
	 * @param message 	信息内容
	 * @return			是否成功
	 * @throws Exception
	 */
	public boolean sendColorMessage(String phone, byte[] message) throws Exception{
		OutboundMessage msg = new OutboundBinaryMessage(phone,message);
		return Service.getInstance().sendMessage(msg);
	}
	/**
	 * 
	 * 功能：发信息
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param phone 	号码（不支持多个）
	 * @param message 	信息内容
	 * @return			是否成功
	 * @throws Exception
	 */
	public boolean sendMessage(String phone, String message) throws Exception{
		OutboundMessage msg = new OutboundMessage(phone,message);
		msg.setEncoding(MessageEncodings.ENCUCS2);
		return Service.getInstance().sendMessage(msg);
	}
	/**
	 * @describe: 给指定的一组手机号码,发送短信
	 * @param phoneList 手机号码列表
	 * @param message 信息内容
	 * @return: true:成功 false:失败
	 * @date:2010-3-1
     */
	public boolean sendMessage(List<String> phoneList, String message) {
		boolean rsbool = true;

		// 把手机号码逐个加入到短信发送组中
		for (String phone : phoneList) {
			Service.getInstance().addToGroup(SEND_SMS_GROUP, phone);
		}
		OutboundMessage msg = new OutboundMessage(SEND_SMS_GROUP, message);
		msg.setEncoding(MessageEncodings.ENCUCS2);
		
		try {
			Service.getInstance().sendMessage(msg);

			// 发送完短信,把手机号码逐个从短信发送组中移除
			for (String phone : phoneList) {
				Service.getInstance().removeFromGroup(SEND_SMS_GROUP, phone);
			}
		} catch (Exception e) {
			rsbool = false;
			e.printStackTrace();
		}
		return rsbool;
	}
	/**
	 * 
	 * 功能：发信息
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param msg
	 * @param functionNum	功能代码
	 * @return			是否成功
	 * @throws Exception
	 */
//	public boolean sendMessage(OutboundMessage msg,String functionNum) throws Exception{
//		boolean ret = false;
//		if(functionNum!=null&&!"".equals(functionNum)&&""!=functionNum){
//			//读取配置文件取手机号码对应的cgsn
//			String cgsn = PropertyUtil.getValues("common_conf.properties","function.num."+functionNum);
//			String gatewayId = "modem."+SendMessageFacadeImpl.getInstance().comMap.get(cgsn);
//			System.out.println("发送网关："+gatewayId);
//			System.out.println("发送cgsn："+cgsn);
//			ret = Service.getInstance().sendMessage(msg,gatewayId);
//		}else{
//			//读取配置文件取手机号码对应的cgsn
//			String cgsn = PropertyUtil.getValues("common_conf.properties","function.num.other");
//			String gatewayId = "modem."+SendMessageFacadeImpl.getInstance().comMap.get(cgsn);
//			System.out.println("发送网关："+gatewayId);
//			System.out.println("发送cgsn："+cgsn);
//			ret = Service.getInstance().sendMessage(msg,gatewayId);
//			
////			ret = Service.getInstance().sendMessage(msg);
//		}
//		return ret;
//	}
	/**
	 * 
	 * 功能：发信息
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param msg
	 * @return			是否成功
	 * @throws Exception
	 */
	public boolean sendMessage(OutboundMessage msg) throws Exception{
		return Service.getInstance().sendMessage(msg);
	}
	/**
	 * 
	 * 功能：发信息（群发）
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param msgs
	 * @return			返回发送成功数
	 * @throws Exception
	 */
	public int sendMessages(Collection<OutboundMessage> msgs) throws Exception{
		return Service.getInstance().sendMessages(msgs);
	}
	/**
	 * 
	 * 功能：发信息（群发）
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param msgs
	 * @return			返回发送成功数
	 * @throws Exception
	 */
	public int sendMessages(OutboundMessage[] msgs) throws Exception{
		return Service.getInstance().sendMessages(msgs);
	}
	/**
	 * 
	 * 功能: 是否已启动
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @return
	 */
	public boolean isStarted() {
		if (Service.getInstance().getServiceStatus() == Service.ServiceStatus.STARTED) {
			for (AGateway gateway : Service.getInstance().getGateways()) {
				if (gateway.getStatus() == AGateway.GatewayStatuses.STARTED) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 
	 * 功能：读取信息
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @return
	 * @throws Exception
	 */
	public List<InboundMessage> readMessages() throws Exception {
		List<InboundMessage> msgList = new LinkedList<InboundMessage>();
		if (!isStarted()) {
			return msgList;
		}
		Service.getInstance().readMessages(msgList,
					InboundMessage.MessageClasses.ALL);
		return msgList;
	}
	/**
	 * 
	 * 功能：删除信息
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @param msg
	 * @return 返回是否成功
	 * @throws Exception
	 */
	public boolean deleteMessage(InboundMessage msg) throws Exception{
		return Service.getInstance().deleteMessage(msg);
	}
	/**
	 * 
	 * 功能：停止服务
	 * @author: cyf
	 * @Date: 2013-1-5
	 *
	 * @throws Exception
	 */
	public void stopService() throws Exception{
		if(isStarted()){
			Service.getInstance().stopService();
			Collection<AGateway> gateways = Service.getInstance().getGateways();
			Object[] array = (Object[]) gateways.toArray();
			for (int i = 0;i < array.length; i++) {
				AGateway gateway = (AGateway) array[i];
				Service.getInstance().removeGateway(gateway);//将网关在短信猫服务中移除
			}
		}
	}

	/**
	 * 作用 : 收短信的监听,并删除收到的短信
	 */
	public class InboundNotification implements IInboundMessageNotification {
		public void process(AGateway gateway, MessageTypes msgType, InboundMessage msg) {
			System.out.println(msg);
			try{
				//处理收到的短信
				ParseMessageFacadeImpl.parse(msg.getOriginator(),"",msg.getText());
			}catch (Exception e) {
				System.out.println("不是文本信息");
			}finally{
				// 删除收到的短信
				if (rec_msg_remove){ // 删除收到的短信
					try {
						Service.getInstance().deleteMessage(msg);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	/**
	 * 发短信监听
	 */
	public class OutboundNotification implements IOutboundMessageNotification {

		public void process(AGateway gateway, OutboundMessage msg){
			System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
			System.out.println("---------->" + msg);
		}
	}
}
